package sendSms

import (
	"encoding/json"
	"fmt"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/regions"
	sms "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/sms/v20210111"
	"math/rand"
	"net/http"
	"strconv"
	"time"
)

//	TxSendSms
//
// 描述信息：腾讯发送短信验证码
//
// Param：
//
//	phones ：手机号码
//	params ：验证码
//
// Return：
//
//	sendRes ：发送请求的响应结果
//	boolean ：成功或者失败
//
// TxSendSms 发送短信验证码
// TxSendSms 发送短信验证码
func TxSendSms(phone, code string) (sendRes string, success bool) {
	cpf := profile.NewClientProfile()
	cpf.HttpProfile.Endpoint = "sms.tencentcloudapi.com"
	cpf.HttpProfile.ReqMethod = http.MethodPost
	client, err := sms.NewClient(common.NewCredential("AKIDCIMJC68CMj4IiIzjPzStCUpEat7OHHGD",
		"PylVueUIJTbqcLA8FQkF3rraEylorr1C"), regions.Beijing, cpf)
	if err != nil {
		fmt.Printf("Failed to create client: %s\n", err)
		return "", false
	}

	request := sms.NewSendSmsRequest()
	request.TemplateId = common.StringPtr("2274472")
	request.TemplateParamSet = common.StringPtrs([]string{code})
	request.SmsSdkAppId = common.StringPtr("1400935669")
	request.SignName = common.StringPtr("北京财童到家科技")
	request.PhoneNumberSet = common.StringPtrs([]string{fmt.Sprintf("+86%s", phone)})

	response, err := client.SendSms(request)
	if err != nil {
		fmt.Printf("An API error occurred: %s", err)
		return "", false
	}
	if *response.Response.SendStatusSet[0].Code != "Ok" {
		fmt.Printf("不允许重复发送: %s", *response.Response.SendStatusSet[0].Message)
		return "", false
	}
	dat := map[string]interface{}{}
	content := response.ToJsonString()
	if errs := json.Unmarshal([]byte(content), &dat); errs != nil {
		fmt.Printf("Failed to unmarshal response: %s", errs)
		return "", false
	}

	fmt.Printf("Send SMS response: %s", response.ToJsonString())

	sendRes = content
	success = true
	return
}

// RandInt64 返回一个在[min, max]范围内的随机int64整数
func RandInt64(min, max int64) int64 {
	rand.Seed(time.Now().UnixNano())
	return min + rand.Int63n(max-min+1)
}
func main() {
	// 定义手机号码
	phoneNumber := "18214814408"

	// 生成随机验证码
	phoneCode := RandInt64(100000, 999999)

	fmt.Printf("Generated phone code: %d\n", phoneCode)

	// 调用 TxSendSms 函数发送短信
	sendRes, success := TxSendSms(phoneNumber, strconv.FormatInt(phoneCode, 10))
	if success {
		fmt.Println("短信发送成功，响应内容：", sendRes)
	} else {
		fmt.Println("短信发送失败，响应内容：", sendRes)
	}
}
